package com.kaede.hayate.security.jwt;

import com.kaede.hayate.config.ApplicationProperties;
import com.kaede.hayate.security.entity.RestUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class JwtFilter extends OncePerRequestFilter {

    private JwtService jwtService;

    private ApplicationProperties applicationProperties;

    public JwtFilter(JwtService jwtService, ApplicationProperties applicationProperties) {
        this.jwtService = jwtService;
        this.applicationProperties = applicationProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = resolveToken(request);
        if(!StringUtils.isEmpty(jwt)){
            RestUserDetails restUserDetails = (RestUserDetails) jwtService.getUserDetails(jwt, request);
            if(restUserDetails != null){
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        restUserDetails, Long.parseLong(restUserDetails.getUserId()), restUserDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                        request));
                SecurityContextHolder.getContext().setAuthentication(authentication);

                request.setAttribute("userId", restUserDetails.getUserId());
                request.setAttribute("username", restUserDetails.getUsername());
            }
        }
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request){
        String bearerToken = request.getHeader(applicationProperties.getAuthorizationHeader());
        String tokenPrefix = applicationProperties.getTokenPrefix();
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(tokenPrefix)) {
            return bearerToken.substring(tokenPrefix.length(), bearerToken.length());
        }
        return null;
    }
}
